﻿#include "utilityWriteToFile.hpp"

#include <stdarg.h>

using namespace std;

void UTILITY::addFileNameWithProcID(Communicator *comm, char *fileName) {
  std::ostringstream os;
  int myID = comm->getMyId();
  os << fileName << "_" << myID << ".txt";
  strcpy(fileName, os.str().c_str());
}

void UTILITY::writeToFileLabel(Communicator *comm, const char *fileName, int n,
                               int len, ...) {
  va_list argsPtr;
  va_start(argsPtr, len);
  ofstream out;
  char fileNameNew[50];
  strcpy(fileNameNew, fileName);
  addFileNameWithProcID(comm, fileNameNew);
  out.open(fileNameNew, ios::out);
  out << "nVars: " << n << ", length: " << len << "\n";

  int **arr = new int *[n];

  for (int i = 0; i < n; ++i) {
    arr[i] = va_arg(argsPtr, int *);
  }

  for (int i = 0; i < len; ++i) {
    for (int j = 0; j < n; ++j) {
      out << arr[j][i];
      if (j != n - 1) out << " ";
    }
    out << "\n";
  }
  delete[] arr;
  va_end(argsPtr);
  out.close();
}

void UTILITY::writeToFileScalar(Communicator *comm, const char *fileName, int n,
                                int len, ...) {
  va_list argsPtr;
  va_start(argsPtr, len);
  ofstream out;
  char fileNameNew[50];
  strcpy(fileNameNew, fileName);
  addFileNameWithProcID(comm, fileNameNew);
  out.open(fileNameNew, ios::out);
  out << "nVars: " << n << ", length: " << len << "\n";

  double **arr = new double *[n];

  for (int i = 0; i < n; ++i) {
    arr[i] = va_arg(argsPtr, double *);
  }

  for (int i = 0; i < len; ++i) {
    for (int j = 0; j < n; ++j) {
      out << arr[j][i];
      if (j != n - 1) out << " ";
    }
    out << "\n";
  }
  delete[] arr;
  va_end(argsPtr);
  out.close();
}
